package com.star.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.star.constant.MessageConstant;
import com.star.constant.StatusConstant;
import com.star.context.BaseContext;
import com.star.dto.BusinessDTO;
import com.star.dto.BusinessLoginDTO;
import com.star.dto.BusinessPageQueryDTO;
import com.star.dto.PasswordEditDTO;
import com.star.entity.Business;
import com.star.exception.AccountLockedException;
import com.star.exception.AccountNotFoundException;
import com.star.exception.OrderBusinessException;
import com.star.exception.PasswordErrorException;
import com.star.mapper.BusinessMapper;
import com.star.result.PageResult;
import com.star.service.BusinessService;
import com.star.vo.user.BusinessVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;

@Service
public class BusinessServiceImpl implements BusinessService {

    @Autowired
    private BusinessMapper businessMapper;

    /**
     * 商家登录
     *
     * @param businessLoginDTO
     * @return
     */
    public Business login(BusinessLoginDTO businessLoginDTO) {
        String username = businessLoginDTO.getUsername();
        String password = businessLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Business business = businessMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (business == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        //对前端传来的密码进行加密与数据库密码比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(business.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (business.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return business;
    }

    /**
     * 新增商家
     * @param businessDTO
     */
    public void add(BusinessDTO businessDTO) {
        Business business = new Business();

        // 对象属性拷贝
        BeanUtils.copyProperties(businessDTO, business);

        // 设置账户状态, 默认状态 1:正常 0:禁用
        business.setStatus(StatusConstant.ENABLE);

        // 设置默认密码: 身份证后六位
        String idNumber = business.getIdNumber();
        business.setPassword(DigestUtils.md5DigestAsHex(idNumber.substring(idNumber.length() - 6).getBytes()));
        
        // 公共字段自动注入
//        // 设置当前记录的创建时间和修改时间
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
//
//        // 设置当前记录的创建人id和修改人id
//        employee.setCreateUser(BaseContext.getCurrentId());
//        employee.setUpdateUser(BaseContext.getCurrentId());

        businessMapper.insert(business);
    }

    /**
     * 商家分页查询
     * @param businessPageQueryDTO
     * @return
     */
    public PageResult pageQuery(BusinessPageQueryDTO businessPageQueryDTO) {
        // 开启分页查询
        PageHelper.startPage(businessPageQueryDTO.getPage(), businessPageQueryDTO.getPageSize());
        Page<Business> page = businessMapper.pageQuery(businessPageQueryDTO);
        long total = page.getTotal();
        List<Business> records = page.getResult();
        return new PageResult(total, records);
    }

    /**
     * 启用禁用员工状态
     * @param status
     * @param id
     */
    public void updateStatus(Integer status, Long id) {
        Business business = new Business();
        business.setStatus(status);
        business.setId(id);
        businessMapper.update(business);
    }

    /**
     * 根据id查询员工信息
     * @param id
     */
    public Business getById(Long id) {
        Business business = businessMapper.getById(id);
        if(business == null) {
            throw new OrderBusinessException(MessageConstant.BUSINESS_NOT_FOUND);
        }
        return business;
    }

    /**
     * 更新员工信息
     * @param businessDTO
     */
    public void update(BusinessDTO businessDTO) {
        // 属性拷贝
        Business business = new Business();
        BeanUtils.copyProperties(businessDTO, business);

        // 公共字段自动注入
//        // 设置当前记录的修改时间和修改人id
//        employee.setUpdateTime(LocalDateTime.now());
//        employee.setUpdateUser(BaseContext.getCurrentId());

        businessMapper.update(business);
    }

    /**
     * 更新账户密码
     * @param passwordEditDTO
     */
    public void updatePwd(PasswordEditDTO passwordEditDTO) {
        passwordEditDTO.setId(BaseContext.getCurrentId());
        Business business = businessMapper.getById(passwordEditDTO.getId());
        // 加密输入旧密码
        String oldPwd = DigestUtils.md5DigestAsHex(passwordEditDTO.getOldPassword().getBytes());
        if(!oldPwd.equals(business.getPassword())) {
            // 原密码错误
            throw new PasswordErrorException(MessageConstant.OLD_PASSWORD_ERROR);
        }
        // 更新密码
        business.setPassword(DigestUtils.md5DigestAsHex(passwordEditDTO.getNewPassword().getBytes()));

        // 公共字段自动注入:update_time,update_user

        businessMapper.update(business);
    }

    /**
     * 修改头像
     * @param avatar
     */
    public void updateAvatar(Long id, String avatar) {
        Business business = businessMapper.getById(id);
        business.setAvatar(avatar);
        businessMapper.update(business);
    }



    // 用户C端
    /**
     * 商家分页查询
     */
    public PageResult userPageQuery(BusinessPageQueryDTO businessPageQueryDTO) {
        // 开启分页查询
        PageHelper.startPage(businessPageQueryDTO.getPage(), businessPageQueryDTO.getPageSize());
        Page<BusinessVO> page = businessMapper.userPageQuery(businessPageQueryDTO);

        long total = page.getTotal();
        List<BusinessVO> records = page.getResult();
        return new PageResult(total, records);
    }
}
